package com.culture.config.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.culture.config.common.util.ExceptionUtil;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.scheduling.support.CronSequenceGenerator;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class CronUtil {    

    public void validExpression(final String expression){
        ExceptionUtil.businessExceptionWhenTrue(!CronSequenceGenerator.isValidExpression(expression), "Corn is not a valid expression.");
    } 

    public List<Date> getCronScheduleTimes(final String expression,final int count){
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(expression);
        Date nextDate = new Date();
        List<Date> dates = new ArrayList<>(count);
        for(int i= 0 ; i< count; i++){
            nextDate = cronSequenceGenerator.next(nextDate);
            dates.add(nextDate);
        }
        return dates;
    }

    public List<String> printCronScheduleTimes(final String expression){
        List<Date> dates = getCronScheduleTimes(expression,10);
        List<String> dateList = new ArrayList<>(10);
        dates.forEach(d->{
            String dateStr = DateFormatUtils.format(d, "yyyy-MM-dd HH:mm:ss.SSS");
            dateList.add(dateStr);
            log.info("[{}]NextScheduleTime:{}", expression, dateStr );           
        });
        return dateList;
    }
    
}
    
    
